package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.cloudfun.campusshare.common.model.dto.kjt.KjtPaymentNotifyDTO;
import com.cloudfun.campusshare.entity.KjtPaymentEntity;
import com.cloudfun.campusshare.repo.KjtPaymentRepo;
import com.cloudfun.campusshare.service.KjtPaymentService;
import com.cloudfun.campusshare.util.AmountUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * Created by Huqin on 2020/8/12
 */
@Slf4j
@Service
public class KjtPaymentServiceImpl implements KjtPaymentService {

    @Autowired
    private KjtPaymentRepo paymentNotifyRepo;

    @Override
    public void create(KjtPaymentNotifyDTO notifyDTO) {
        KjtPaymentEntity notifyEntity = paymentNotifyRepo.findByNotifyId(notifyDTO.getNotifyId());
        if (null == notifyEntity) {
            notifyEntity = new KjtPaymentEntity();
            BeanUtil.copyProperties(notifyDTO, notifyEntity, "tradeAmount", "gmtCreate", "gmtPayment", "gmtClose");
        } else {
            BeanUtil.copyProperties(notifyDTO, notifyEntity, CopyOptions.create().setIgnoreNullValue(true).setIgnoreProperties("tradeAmount", "gmtCreate", "gmtPayment", "gmtClose"));
        }
        notifyEntity.setOuterTradeNo(notifyDTO.getInnerTradeNo());
        notifyEntity.setOrderNo(notifyDTO.getOuterTradeNo());
        notifyEntity.setTradeAmount(AmountUtil.strAmount2Int(notifyDTO.getTradeAmount()));
        notifyEntity.setGmtCreate(LocalDateTime.parse(notifyDTO.getGmtCreate(), KjtPaymentNotifyDTO.GMT_CREATE_FORMATTER));
        if (StringUtils.isNotBlank(notifyDTO.getGmtPayment())) {
            notifyEntity.setGmtPayment(LocalDateTime.parse(notifyDTO.getGmtPayment(), KjtPaymentNotifyDTO.GMT_PAYMENT_FORMATTER));
        }
        if (StringUtils.isNotBlank(notifyDTO.getGmtClose())) {
            notifyEntity.setGmtClose(LocalDateTime.parse(notifyDTO.getGmtClose(), KjtPaymentNotifyDTO.GMT_CLOSE_FORMATTER));
        }
        paymentNotifyRepo.save(notifyEntity);
    }

}
